/**
 * ***********************************************************************
 * Copyright:2016-2018 DongLBS Inc. All rights reserved.
 * Author:Riven
 * CreateData:2017-06-09 12:14
 * Version:v0.0.8
 * Description:主界面
 * ***********************************************************************
 */
<template>
  <f7-page data-name="home" :page-content="false">
    <f7-navbar>
      <f7-nav-left>
        <f7-link icon-if-ios="f7:menu" icon-if-md="material:menu" panel-open="left"></f7-link>
      </f7-nav-left>
      <f7-nav-title>{{$t("common.appName")}}<span class="trademark">®</span></f7-nav-title>
      <f7-nav-right>
        <f7-link  href="/events/"><f7-icon f7="bell" size="20px"><f7-badge color="red">{{$store.state.events.unReadCount}}</f7-badge></f7-icon></f7-link>
      </f7-nav-right>
    </f7-navbar>
    <div id="lbsmap">
        <lbs-map ref="lbsmap" :maptype="$store.state.map.type" :lang="$store.state.global.lang" :center="$store.state.map.center" :zoom="$store.state.map.zoom" @onClick="onClickMarker">
          <lbs-marker

            :coord="myPosition.coord"
            color="#007aff"
            :angle="180"
            :visible="myPosition.visible">
            </lbs-marker>
          <lbs-marker v-for="(device,index) in $store.state.devices.list"
        		:key="index"
        		:id="device.id"
        		:coord="device.marker.coord"
        		:label="device.marker.label"
        		:color="device.marker.color"
        		:angle="device.marker.angle"
        		:visible="device.marker.visible">
        		</lbs-marker>

             <lbs-popup :header="$store.state.popup.header" :topRight="$store.state.popup.topRight" :coord="$store.state.popup.coord" :content="$store.state.popup.content" :footer="$store.state.popup.footer" :visible="$store.state.popup.visible"></lbs-popup>
             <lbs-circle
									 :id="1"
									 :visible="circle.visible"
									 :coords="circle.coord"
									 :radius="circle.radius"
									 :strokeColor="circle.strokeColor"
									 :fillColor="circle.fillColor"
									 ></lbs-circle>
            <lbs-line :coords="findCarLine"></lbs-line>
        </lbs-map>
        <f7-fab position="right-bottom" slot="fixed" color="blue">
          <f7-icon ios="f7:add" md="material:add"></f7-icon>
          <f7-icon ios="f7:close" md="material:close"></f7-icon>
          <f7-fab-buttons position="top" v-show = "$store.state.devices.selectId!=0&&$store.state.map.mode==1">
            <f7-fab-button :label="$t('home.stopTracking')" @click="$store.dispatch('setMapValue', [{key:'mode',value:0}])"><f7-icon f7="logout" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button :label="$t('home.historyPosition')" @click="playHistory"><f7-icon f7="videocam" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button :label="$t('home.deviceInfo')" @click="$f7router.navigate('/device-info/')"><f7-icon f7="compose" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button :label="$t('home.commandSending')" @click="showCommands"><f7-icon f7="download" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button :label="$t('home.streetView')" @click="$f7router.navigate('/streetview/')"><f7-icon f7="eye" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button :label="$t('home.vehicleDistance')" @click="findCar"><f7-icon f7="paper_plane" size="18px" :color="this.timer==null?'':'yellow'"></f7-icon></f7-fab-button>
          </f7-fab-buttons>
          <f7-fab-buttons position="left" v-show = "$store.state.map.mode==0">
            <f7-fab-button  @click="geoloction"><f7-icon f7="compass" size="18px"></f7-icon></f7-fab-button>
            <f7-fab-button ><f7-icon f7="camera" size="18px"></f7-icon></f7-fab-button>
          </f7-fab-buttons>
        </f7-fab>


        <!-- Grid -->
        <f7-actions :grid="true" :opened="actionGridOpened" @actions:closed="actionGridOpened = false">
          <f7-actions-group>
            <f7-actions-button v-for="(view,index) in commandViews" @click="showCommandView(view.id)">
              <f7-icon slot="media" f7="cloud_download" size="32px"></f7-icon>
              <span>{{view.label}}</span>
            </f7-actions-button>



          </f7-actions-group>
        </f7-actions>

    </div>


  </f7-page>
</template>
<script>
import Vue from 'vue'
import moment from 'moment'
export default {
  data() {
			return {
					selectDeviceId:null,
          circle:{
							visible:false,
	 						coord:[117.19996, 31.797646],
	 						radius:1110,
	 						strokeColor:'#409EFF',
	 						fillColor:'rgba(64,158,255, 0.2)'
						},
            myPosition:{
             coord: [117.12996, 31.197646],
             color:'#409EFF',
             visible:false
           },
           actionGridOpened: false,
           findCarLine:[],
           timer:null,
           commandViews:[]

			}
		},
  methods:{

    onClickMarker(feature){
				if(feature.getId()){
					switch (feature.get('type')) {
						case 'marker'://点击车辆marker
							this.selectDeviceId = feature.getId();
							this.$store.dispatch('setSelectDeviceId', feature.getId());
							break;
						case 'stopicon'://点击轨迹回放停留标注
							if(feature.getId().indexOf("stop")!=-1){
								//var ele = document.getElementById('stop'+feature.getId().split(':')[1]);
								 //ele.setAttribute("style",ele.getAttribute('style')=='display:block'?"display:none":"display:block");
							}
							break;
						case 'poi'://点击兴趣点
							//this.$store.dispatch('setPoiValue',{key:'selectId',value:feature.getId()});
							break;
						default:

					}
				}
			},
      showInfinite(b) {
       const self = this;
       const app = self.$f7;

       if(b){
         if (self.infiniteLoading) return;
         self.infiniteLoading = true;
         app.progressbar.show('multi');

       }else{
         self.infiniteLoading = false;
         app.progressbar.hide();
       }

     },
      geoloction(){
          this.showInfinite(true);

					 if (!Vue.cordova.geolocation) {
             this.$f7.toast.create({
                text: '定位异常',
                closeTimeout: 2000,
              }).open();
                this.showInfinite(false);
							return
						}
						Vue.cordova.geolocation.getCurrentPosition((position) => {
							let center = [position.coords.longitude, position.coords.latitude];
							this.$store.dispatch('setMapValue',[{'key':'center','value':center},{'key':'zoom','value':16}]);
							this.myPosition.coord =center;
              this.myPosition.visible = true;
							this.circle ={
							 visible:true,
							 coord:center,
							 radius:position.coords.accuracy,
							 strokeColor:'#409EFF',
							 fillColor:'rgba(64,158,255, 0.2)'
						 }
               this.showInfinite(false);

						}, (error) => {
              this.$f7.toast.create({
                 text: '定位失败 #' + error.code + ' ' + error.message,
                 closeTimeout: 2000,
               }).open();
                 this.showInfinite(false);
						}, {
							timeout: 60000,
							enableHighAccuracy: true
						})
				 },
         playHistory(){
						var  _this = this;
						setTimeout(function(){
								 _this.calendarDefault.open();
						});
					},
          exitTrack(){

          },
          initCalendar(){
            var _this =this;
            this.calendarDefault =  this.$f7.calendar.create({
                 inputEl: '#calendar-modal',
                 openIn: 'customModal',
                 headerPlaceholder:'请选择日期',
                 toolbarCloseText:'完成',
                 header: true,
                 footer: true,
                 dateFormat: 'yyyy M dd',
                 monthNames:['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月' , '九月' , '十月', '十一月', '十二月'],
                 monthNamesShort:['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月' , '9月' , '10月', '11月', '12月'],
                 dayNamesShort:['周日','周一','周二','周三','周四','周五','周六'],
                 rangePicker: true,
                 on: {

                   closed(p){
                     if(p.value){
                       let startTime = moment(p.value[0]).format('YYYY-MM-DD HH:mm:ss');
                       let endTime = p.value[1]?moment(p.value[1]).add('hours',23).format('YYYY-MM-DD HH:mm:ss'):moment(p.value[0]).add('hours',23).format('YYYY-MM-DD HH:mm:ss');
                       window.f7.router.navigate({url: '/historys/?startTime='+startTime+'&endTime='+endTime})
                     }
                   },
                   change(c){
                   }
                  }
               })
          },
          watchPosition(){
            this.showInfinite(true);
             var _this =this;
            _this.timer = navigator.geolocation.watchPosition(function(position){//成功
              _this.findCarLine=[]

              let center = [position.coords.longitude, position.coords.latitude];
               _this.$store.dispatch('setMapValue',[{'key':'center','value':center},{'key':'zoom','value':16}]);
               _this.myPosition.coord =center;
                _this.myPosition.visible = true;
               _this.circle ={
                visible:true,
                coord:center,
                radius:position.coords.accuracy,
                strokeColor:'#409EFF',
                fillColor:'rgba(64,158,255, 0.2)'
              }

              let devicePosition = []
              let my = _this.myPosition.coord
              let device = _this.$store.state.devices.list[_this.$store.state.devices.index[_this.$store.state.devices.selectId]];
              if(device.position){
                  devicePosition = [device.position.longitude,device.position.latitude]
              }
              _this.findCarLine = [my,devicePosition];
              // _this.$f7.toast.create({
              //    text: '定位成功'+_this.findCarLine,
              //    closeTimeout: 2000,
              //  }).open();
             },function(error){
               _this.$f7.toast.create({
                  text: '定位失败 #' + error.code + ' ' + error.message,
                  closeTimeout: 2000,
                }).open();
                 //清除多次地理位置定位
                 if(_this.timer){
                    navigator.geolocation.clearWatch(_this.timer);
                    _this.timer=null;
                 }

             },{
                 /*数据收集 :  json的形式
                  enableHighAcuracy  :  更精确的查找，默认false
                  timeout  :指定获取地理位置的超时时间，默认不限时，单位为毫秒
                  maximumAge :最长有效期，在重复获取地理位置时，此参数指定多久再次获取位置。
              */
             enableHighAccuracy:true,
             maximumAge:2000
             });

            this.showInfinite(false);



          },
          findCar(){
            if(this.timer==null){
                this.watchPosition();
            }else{
               navigator.geolocation.clearWatch(this.timer);
               this.timer=null;
               this.findCarLine = []
               this.circle.visible=false;
               this.myPosition.visible = false;
            }
          },
          showCommands(){
            this.actionGridOpened = true
            this.commandViews=[];
            var device = this.$store.state.devices.list[this.$store.state.devices.index[this.$store.state.devices.selectId]];
            var cmdIds = this.$store.state.dict.commandIdsByType[device.typeId];
            var cmdViews = this.$store.state.dict.commandViews;
              if(cmdIds){
  				      	 cmdIds.forEach(cmdId => {
                       this.commandViews.push({
                         id:cmdId,
                         label:cmdViews[cmdId].name
                       })
  		              });

			      	}else{
                  this.actionGridOpened = false;
                  this.$f7.toast.create({
                     text: '无有效指令',
                     closeTimeout: 2000,
                   }).open();
              }
          },
          showCommandView(id){
              //console.log(id);
              this.$f7.router.navigate('/commandview/?id='+id)
          }

  },
  created(){
  },
   mounted() {

      this.initCalendar();

   },
   watch: {

			//模式切换
			'$store.state.map.mode': function(nv, ov) {
				console.log('切换模式为：'+ov+'--> '+nv);
        if(nv==0&&ov==1){//跟踪模式->全局监控
          if(this.$store.state.popup.visible){
              //console.log('取消跟踪');
              this.$store.dispatch('isShowBoubble');
            }
            //关闭画面跟随
            if(this.$store.state.map.isTrackCenter){
               this.$store.dispatch('setMapValue',[{'key':'isTrackCenter','value':false}]);
            }
        }else if(nv==1&&ov==0){
            this.$store.dispatch('setMapValue',[{'key':'isTrackCenter','value':true}]);
        }

			}
		},
    beforeDestroy () {

    },
}
</script>
<style>

#lbsmap {
	width: 100%;
  height: 100%;
}
#lbsmap > div:first-child {
		height: 100%;
}

.lbs-popup {
    margin: -132px -82px;
    position:fixed;

}
.lbs-popup ul li {
 line-height:14px;
  white-space:nowrap;
}


.bubble-icon{
    width: 16px;
    height: 18px;
    vertical-align: -5px;
    overflow: hidden;
    margin-left: 2px;
}



   /** 电量  begin 2017-03-29**/
.battery {
   color: #34495e;
   border: 1px solid currentColor;
   display: inline-block;
   width: 20px;
   height: 10px;
   position: relative;
   border-radius: 2px;
   margin: 0px;
   transition: color 500ms;
}
.battery::before,
.battery::after {
   content: "";
   position: absolute;
}
.battery::before {
   top: 2px;
   bottom: 2px;
   right: -3px;
   width: 1px;
   display: border-box;
   border: 1px solid currentColor;
   border-left: 0;
}
.battery::after {
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
   margin: 1px;
   border-radius: 1px;
   background-color: currentColor;
   transition: right 500ms;
}
.battery.low {
   color: #c0392b;
}
.battery.low::after {
   right: 80%;
   border-top-right-radius: 0;
   border-bottom-right-radius: 0;
}
.battery.med {
   color: #f39c12;
}
.battery.med::after {
   right: 40%;
   border-top-right-radius: 0;
   border-bottom-right-radius: 0;
}
.battery.full {
   color: #27ae60;
}
.battery[data-charge='none']{
 display: none !important;
}
.battery[data-charge='0'],
.battery[data-charge='1'],
.battery[data-charge='2']{
   color: #c0392b;
}
.battery[data-charge='3'],
.battery[data-charge='4'] {
   color: #f39c12;
}
.battery[data-charge='5'],
.battery[data-charge='6'],
.battery[data-charge='9'] {
   color: #27ae60;
}
.battery[data-charge='0']::after {
   right: 100%;
}
.battery[data-charge='1']::after {
   right: 83%;
}
.battery[data-charge='2']::after {
   right: 67%;
}
.battery[data-charge='3']::after {
   right: 50%;
}
.battery[data-charge='4']::after {
   right: 33%;
}
.battery[data-charge='5']::after {
   right: 17%;
}
.battery[data-charge='6']::after {
   right: 0%;
}
</style>
